package de.slothsoft.commons;

import java.text.NumberFormat;
import java.util.Collection;
import java.util.Iterator;

public class DisplayUtil {

	private static NumberFormat integerFormat;
	private static NumberFormat decimalFormat;

	static {
		integerFormat = NumberFormat.getIntegerInstance();
		integerFormat.setGroupingUsed(false);

		decimalFormat = NumberFormat.getInstance();
		decimalFormat.setGroupingUsed(true);
		decimalFormat.setMinimumIntegerDigits(1);
		decimalFormat.setMaximumIntegerDigits(3);
	}

	public static String toString(Object value) {
		// TODO: optimize
		if (value instanceof Number) {
			if (value instanceof Integer || value instanceof Short || value instanceof Long) {
				return integerFormat.format(value);
			} else {
				return decimalFormat.format(value);
			}
		} else if (value instanceof IDisplayable) {
			return ((IDisplayable) value).getDisplayName();
		} else if (value instanceof Collection<?>) {
			Collection<?> collection = (Collection<?>) value;
			StringBuilder sb = new StringBuilder();
			int i = 0;
			for (Iterator<?> it = collection.iterator(); it.hasNext();) {
				Object object = it.next();
				if (i > 0) {
					sb.append(", ");
				}
				sb.append(toString(object));
				i++;
			}
			return sb.toString();
		} else if (value instanceof char[]) {
			return new String((char[]) value);
		} else if (value instanceof double[]) {
			return arrayToString((double[]) value);
		} else if (value instanceof int[]) {
			StringBuilder sb = new StringBuilder();
			int i = 0;
			for (int object : (int[]) value) {
				if (i > 0) {
					sb.append(", ");
				}
				sb.append(object);
				i++;
			}
			return sb.toString();
		} else if (value instanceof Object[]) {
			return arrayToString((Object[]) value);
		}

		return value == null ? null : value.toString();
	}

	public static <T> String arrayToString(T[] array) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (T object : array) {
			if (i > 0) {
				sb.append(", ");
			}
			sb.append(toString(object));
			i++;
		}
		return sb.toString();
	}

	public static String arrayToString(double[] array) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (double object : array) {
			if (i > 0) {
				sb.append(", ");
			}
			sb.append(object);
			i++;
		}
		return sb.toString();
	}
}
